<template>
  <div class="department-container">
    <el-card class="department-card">
      <template #header>
        <div class="department-header">
          <h1>部门管理</h1>
          <el-form :inline="true" :model="searchForm" class="department-filter" @submit.prevent>
            <el-form-item label="部门名称">
              <el-input v-model="searchForm.departmentName" placeholder="请输入部门名称" clearable />
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="searchForm.departmentStatus" placeholder="全部" clearable style="width: 120px">
                <el-option label="正常" :value="0" />
                <el-option label="停用" :value="1" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="fetchList">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
          <div class="department-actions">
            <el-button type="success" @click="openAddDialog()">新增</el-button>
            <el-button @click="toggleExpandOrCollapse">展开/折叠</el-button>
          </div>
        </div>
      </template>

      <el-table :data="treeTableData" style="width: 100%" v-loading="loading" border stripe row-key="departmentId"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" :expand-row-keys="expandedRowKeys"
        :default-expand-all="expandAll">
        <el-table-column prop="departmentName" label="部门名称" min-width="180">
          <template #default="{ row }">
            <span>{{ row.departmentName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="displaySorting" label="排序" min-width="80" />
        <el-table-column prop="departmentStatus" label="状态" min-width="80">
          <template #default="{ row }">
            <el-tag :type="row.departmentStatus === 0 ? 'success' : 'info'">
              {{ row.departmentStatus === 0 ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="registerTime" label="创建时间" min-width="160" />
        <el-table-column label="操作" min-width="200">
          <template #default="{ row }">
            <el-button size="small" @click="openEditDialog(row)">修改</el-button>
            <el-button size="small" @click="openAddDialog(row)">新增</el-button>
            <el-button size="small" type="danger" @click="confirmDelete(row)"
              :disabled="row.deptLevel === 0">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="treeTableData.length === 0 && !loading" class="no-data">
        <el-empty description="暂无部门数据" />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="上级部门" prop="superiorId">
          <el-tree-select v-model="form.superiorId" :data="treeTableData"
            :props="{ label: 'departmentName', children: 'children', value: 'departmentId' }" placeholder="请选择上级部门"
            check-strictly style="width: 100%;" clearable />
        </el-form-item>
        <el-form-item label="部门名称" prop="departmentName">
          <el-input v-model="form.departmentName" />
        </el-form-item>
        <el-form-item label="显示排序" prop="displaySorting">
          <el-input-number v-model="form.displaySorting" :min="1" />
        </el-form-item>
        <el-form-item label="负责人" prop="departmentHead">
          <el-input v-model="form.departmentHead" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="部门状态" prop="departmentStatus">
          <el-radio-group v-model="form.departmentStatus">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog title="系统提示" v-model="deleteDialogVisible" width="350px" :close-on-click-modal="false">
      <span>是否确认删除该部门？</span>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="deleteDepartment">确定</el-button>
      </template>
    </el-dialog>

    <!-- 错误提示弹窗 -->
    <el-dialog title="错误" v-model="errorDialogVisible" width="350px" :close-on-click-modal="false" show-close>
      <span>{{ errorMessage }}</span>
      <template #footer>
        <el-button type="primary" @click="errorDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import DepartmentService from '../services/DepartmentService';
import UserService from '../services/UserService';

const searchForm = reactive({
  departmentName: '',
  departmentStatus: undefined,
});

const loading = ref(false);
const expandAll = ref(true);
const expandedRowKeys = ref([]);
const dialogVisible = ref(false);
const dialogTitle = ref('');
const form = reactive({
  departmentId: undefined,
  superiorId: undefined,
  departmentName: '',
  displaySorting: 1,
  departmentHead: '',
  phone: '',
  email: '',
  departmentStatus: 0,
});
const formRef = ref();
const rules = {
  superiorId: [
    { required: true, message: '请选择上级部门', trigger: 'change' }
  ],
  departmentName: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  displaySorting: [
    { required: true, message: '请输入显示排序', trigger: 'blur' },
    { type: 'number', min: 1, message: '排序必须大于0', trigger: 'blur' }
  ],
  departmentHead: [
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
};
const deleteDialogVisible = ref(false);
const deleteRow = ref(null);
const errorDialogVisible = ref(false);
const errorMessage = ref('');

const rawDepartmentList = ref([]); // 原始部门数据
const treeTableData = ref([]); // 树形结构数据
const flatDepartmentList = ref([]); // 扁平化数据用于下拉

function showError(msg) {
  errorMessage.value = msg;
  errorDialogVisible.value = true;
}

function resetSearch() {
  searchForm.departmentName = '';
  searchForm.departmentStatus = undefined;
  fetchList();
}

function collectAllExpandableKeys(list) {
  const keys = [];
  function dfs(nodes) {
    nodes.forEach(node => {
      if (node.children && node.children.length) {
        keys.push(node.departmentId);
        dfs(node.children);
      }
    });
  }
  dfs(list);
  return keys;
}

function toggleExpandOrCollapse() {
  // 判断第一个根节点是否展开
  expandAll.value = !expandAll.value;
  console.log(expandAll.value);
  fetchList();
}

function buildTree(list) {
  // 先排序
  const sorted = [...list].sort((a, b) => a.displaySorting - b.displaySorting);
  // 构建树
  const idMap = {};
  sorted.forEach(item => { idMap[item.departmentId] = { ...item, children: [] }; });
  const tree = [];
  sorted.forEach(item => {
    const node = idMap[item.departmentId];
    if (item.superiorId && idMap[item.superiorId]) {
      idMap[item.superiorId].children.push(node);
    } else {
      tree.push(node);
    }
  });
  return tree;
}

function flattenTree(list) {
  const arr = [];
  function dfs(nodes) {
    nodes.forEach(node => {
      arr.push(node);
      if (node.children && node.children.length) dfs(node.children);
    });
  }
  dfs(list);
  return arr;
}

async function fetchList() {
  loading.value = true;
  try {
    const params = {
      departmentName: searchForm.departmentName,
      departmentStatus: searchForm.departmentStatus,
    };
    const res = await DepartmentService.getDepartmentListWithPage(params);
    if (res.code === 200) {
      rawDepartmentList.value = res.data.list || [];
      treeTableData.value = buildTree(rawDepartmentList.value);
      flatDepartmentList.value = flattenTree(treeTableData.value);
      // 同步展开状态
      if (expandAll.value) {
        expandedRowKeys.value = collectAllExpandableKeys(treeTableData.value);
      } else {
        expandedRowKeys.value = [];
      }
    } else {
      showError(res.data.message || '获取部门列表失败');
    }
  } catch (e) {
    showError(e.message || '获取部门列表失败');
  } finally {
    loading.value = false;
  }
}

function openAddDialog(parentRow) {
  dialogTitle.value = '添加部门';
  Object.assign(form, {
    departmentId: undefined,
    superiorId: parentRow ? parentRow.departmentId : undefined,
    departmentName: '',
    displaySorting: 1,
    departmentHead: '',
    phone: '',
    email: '',
    departmentStatus: 0,
  });
  dialogVisible.value = true;
  // 重置表单验证状态
  nextTick(() => {
    formRef.value?.clearValidate();
  });
}

function openEditDialog(row) {
  dialogTitle.value = '修改部门';
  Object.assign(form, row);
  dialogVisible.value = true;
  // 重置表单验证状态
  nextTick(() => {
    formRef.value?.clearValidate();
  });
}

function closeDialog() {
  dialogVisible.value = false;
  formRef.value?.resetFields();
}

function submitForm() {
  formRef.value.validate(async (valid) => {
    if (!valid) return;
    try {
      if (form.departmentId) {
        // 修改
        const updateData = {
          departmentName: form.departmentName,
          departmentHead: form.departmentHead,
          displaySorting: form.displaySorting,
          departmentStatus: form.departmentStatus,
          superiorId: form.superiorId,
          phone: form.phone,
          email: form.email,
        };
        const res = await DepartmentService.updateDepartment(form.departmentId, updateData);
        if (res.code === 200) {
          dialogVisible.value = false;
          fetchList();
        } else {
          showError(res.data.message || '修改失败');
        }
      } else {
        // 新增
        const addData = {
          departmentName: form.departmentName,
          departmentHead: form.departmentHead,
          displaySorting: form.displaySorting,
          departmentStatus: form.departmentStatus,
          superiorId: form.superiorId,
          phone: form.phone,
          email: form.email,
        };
        const res = await DepartmentService.addDepartment(addData);
        if (res.code === 200) {
          dialogVisible.value = false;
          fetchList();
        } else {
          showError(res.data.message || '创建失败');
        }
      }
    } catch (e) {
      showError(e.message || (form.departmentId ? '修改失败' : '创建失败'));
    }
  });
}

function confirmDelete(row) {
  deleteRow.value = row;
  deleteDialogVisible.value = true;
}

async function deleteDepartment() {
  if (!deleteRow.value) return;
  try {
    const res = await DepartmentService.deleteDepartment(deleteRow.value.departmentId);
    if (res.code === 200) {
      deleteDialogVisible.value = false;
      fetchList();
    } else {
      showError(res.data.message || '删除失败');
    }
  } catch (e) {
    showError(e.message || '删除失败');
  }
}

onMounted(() => {
  UserService.loadCurrentUser();
  fetchList();
});
</script>

<style scoped>
.department-container {
  padding: 0;
  background: #fff;
  min-height: 100vh;
}

.department-card {
  margin: 0;
  border-radius: 0;
  box-shadow: none;
}

.department-header {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.department-filter {
  margin-top: 0;
}

.department-actions {
  margin-top: 10px;
}

.no-data {
  padding: 30px 0;
}
</style>